package br.com.sgmf.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.sgmf.model.NotaFiscal;

@Repository
public class NotaFiscalDAO {

	@PersistenceContext
	private EntityManager manager;

	@Transactional
	public void save(NotaFiscal notaFiscal) {
		manager.persist(notaFiscal);
	}

	@Transactional
	public void update(NotaFiscal notaFiscal) {
		manager.merge(notaFiscal);
	}

	@Transactional
	public void delete(NotaFiscal notaFiscal) {
		notaFiscal = manager.merge(notaFiscal);
		manager.remove(notaFiscal);
	}

	@Transactional(readOnly = true)
	public NotaFiscal findById(Integer id) {
		return manager.find(NotaFiscal.class, id);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<NotaFiscal> findAll() {
		return manager.createNamedQuery("NotaFiscal.findAll").getResultList();
	}

	@Transactional(readOnly = true)
	public List<NotaFiscal> findBetweenDate(Date inicio, Date fim) {
		CriteriaBuilder builder = manager.getCriteriaBuilder();
		CriteriaQuery<NotaFiscal> query = builder.createQuery(NotaFiscal.class);
		Root<NotaFiscal> notaFiscal = query.from(NotaFiscal.class);
		if (inicio != null || fim != null) {
			Expression<Date> data = notaFiscal.get("dataEmissao");
			if (inicio != null && fim != null) {
				query.where(builder.between(data, inicio, fim));
			} else if (inicio != null && fim == null) {
				query.where(builder.greaterThanOrEqualTo(data, inicio));
			} else if (fim != null && inicio == null) {
				query.where(builder.lessThanOrEqualTo(data, fim));
			}
		}
		return manager.createQuery(query).getResultList();
	}

}
